package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.AddressBookBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        //补充地址信息
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = AddressBook
                .builder()
                .userId(BaseContext.getCurrentId())
                .build();
        return addressBookMapper.list(addressBook);
    }

    /**
     * 设置默认地址
     * @param id
     */
    @Override
    @Transactional
    public void setDefault(Long id) {
        //将当前用户下的默认地址设为非默认的
        addressBookMapper.setIsNotDefault(BaseContext.getCurrentId());
        //设置默认地址
        addressBookMapper.setDefault(id);
    }

    /**
     * 获取默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        return addressBookMapper.getDefault(BaseContext.getCurrentId());
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook findById(Long id) {
        return addressBookMapper.findById(id);
    }

    /**
     * 根据id删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        /*//判断当前地址是否为默认地址
        AddressBook addressBook = addressBookMapper.getDefault(BaseContext.getCurrentId());
        if(addressBook.getId() == id){
            throw new AddressBookBusinessException("不能删除默认地址");
        }*/
        addressBookMapper.deleteById(id);
    }

    /**
     * 编辑地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }
}
